﻿using System.Collections.Generic;
using System.Diagnostics;
using Framework;
using UnityEngine;
using UnityEngine.Rendering.Universal;
using UnityEngine.UI;

namespace Game
{
    public class GameUISystem : EventTargetMonoSingleton<GameUISystem>
    {
        public Camera camera { get; private set; }

        public Canvas canvas { get; private set; }

        public RectTransform canvasTransform
        {
            get
            {
                return _transform;
            }
        }

        private GameObject _gameObject;
        private RectTransform _transform;
        private CanvasScaler _scaler;
        // private ViewLayer[] _layers;
        
        public override void Awake()
        {
            base.Awake();
            InitCanvas();
            // InitLayers();
        }

        // public ViewLayer GetLayer(ViewLayerType layerType)
        // {
        //     return _layers[(int)layerType];
        // }
        //
        // public ViewContainer Show(string name, Dictionary<string, object> properties = null)
        // {
        //     ViewDefine viewDefine = ConfigManager.Instance.GetConfig<ViewConfig>().GetDefine(name);
        //     ViewLayer viewLayer = GetLayer(viewDefine.layerType);
        //     ViewContainer viewContainer = viewLayer.Find(name);
        //     if (viewContainer == null)
        //     {
        //         viewContainer = new ViewContainer(viewDefine, properties);
        //     }
        //     viewContainer.controller.ClearPropertys();
        //     if (properties != null)
        //     {
        //         foreach (KeyValuePair<string, object> pair in properties)
        //         {
        //             viewContainer.controller.SetProperty(pair.Key, pair.Value);
        //         }
        //     }
        //     if (!viewContainer.isShowing)
        //     {
        //         viewContainer.PreShow();
        //         if (viewLayer.Contains(viewContainer))
        //         {
        //             viewLayer.SetAsLastSibling(viewContainer);
        //         }
        //         else
        //         {
        //             viewLayer.Add(viewContainer);
        //         }
        //         PauseAllViewBehind(viewContainer);
        //         viewContainer.AddListenerOnce(ViewContainerEvent.ViewProxyShow, OnViewProxyShow);
        //         viewContainer.Show();
        //         Emit(ViewManagerEvent.ViewShow, name);
        //     }
        //     else if (viewContainer.isPause)
        //     {
        //         viewContainer.Resume();
        //         viewContainer.PreShow();
        //         viewLayer.SetAsLastSibling(viewContainer);
        //         PauseAllViewBehind(viewContainer);
        //         Emit(ViewManagerEvent.ViewShow, name);
        //     }
        //     return viewContainer;
        // }
        //
        // public void Close(string name, bool dispose = false)
        // {
        //     ViewContainer viewContainer = FindView(name);
        //     if (viewContainer == null || !viewContainer.isShowing)
        //     {
        //         return;
        //     }
        //     if (viewContainer.isShowing)
        //     {
        //         viewContainer.Close();
        //         ResumeAllViewBehind(viewContainer);
        //     }
        //     if (dispose)
        //     {
        //         viewContainer.Dispose();
        //         ViewLayer viewLayer = GetLayer(viewContainer.viewDefine.layerType);
        //         viewLayer.Remove(viewContainer);
        //     }
        //     Emit(ViewManagerEvent.ViewClose, name);
        // }
        //
        // public void CloseAll()
        // {
        //     for (int i = 0; i < _layers.Length; ++i)
        //     {
        //         _layers[i].CloseAll();
        //     }
        // }
        //
        // public ViewContainer FindView(string name)
        // {
        //     for (int i = 0; i < _layers.Length; ++i)
        //     {
        //         ViewContainer viewContainer = _layers[i].Find(name);
        //         if (viewContainer != null)
        //         {
        //             return viewContainer;
        //         }
        //     }
        //     return null;
        // }
        //
        // public ViewController FindViewController(string name)
        // {
        //     ViewContainer viewContainer = FindView(name);
        //     if (viewContainer == null)
        //     {
        //         return null;
        //     }
        //     else
        //     {
        //         return viewContainer.controller;
        //     }
        // }

        public void InitCanvas()
        {
            GameObject cameraGO = new GameObject("UICamera");
            DontDestroyOnLoad(cameraGO);
            cameraGO.transform.position = new Vector3(-1000f, -1000f, -1000f);
            camera = cameraGO.AddComponent<Camera>();
            camera.clearFlags = CameraClearFlags.Depth;
            camera.backgroundColor = Color.black;
            // camera.cullingMask = LayerUtil.UIMask;
            camera.farClipPlane = 1000f;
            camera.depth = 5;
            camera.orthographic = true;
            UniversalAdditionalCameraData cameraData = camera.GetUniversalAdditionalCameraData();
            cameraData.renderType = CameraRenderType.Overlay;
            UniversalAdditionalCameraData mainCameraData = Camera.main.GetUniversalAdditionalCameraData();
            mainCameraData.cameraStack.Add(camera);

            _gameObject = new GameObject("Canvas", typeof(RectTransform));
            // _gameObject.layer = LayerUtil.UI;
            _transform = _gameObject.transform as RectTransform;
            canvas = _gameObject.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceCamera;
            canvas.worldCamera = camera;
            // canvas.additionalShaderChannels = AdditionalCanvasShaderChannels.Normal | 
            //                                   AdditionalCanvasShaderChannels.Tangent | 
            //                                   AdditionalCanvasShaderChannels.TexCoord1 |
            //                                   AdditionalCanvasShaderChannels.TexCoord2 |
            //                                   AdditionalCanvasShaderChannels.TexCoord3;
            // canvas.sortingLayerID = LayerUtil.UISortingLayer;

            _scaler = _gameObject.AddComponent<CanvasScaler>();
            _scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
            _scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            _scaler.referenceResolution = Const.PreferResolution;
            _scaler.matchWidthOrHeight = 0.5f;
            _gameObject.AddComponent<GraphicRaycaster>();
            DontDestroyOnLoad(_gameObject);
        }

        // public void SetResolution(float x, float y, float matchWidthOrHeight)
        // {
        //     _scaler.referenceResolution = new Vector2(x, y);
        //     _scaler.matchWidthOrHeight = matchWidthOrHeight;
        // }
        //
        // public void AddViewDefine()
        // {
        //     
        // }
        
        // private void InitLayers()
        // {
        //     ViewLayerType[] layerTypes = ViewLayerTypeUtil.LayerTypes;
        //     _layers = new ViewLayer[layerTypes.Length];
        //     for (int i = 0; i < layerTypes.Length; ++i)
        //     {
        //         ViewLayer viewLayer = new ViewLayer(ViewLayerTypeUtil.GetLayerName(layerTypes[i]));
        //         viewLayer.AddTo(_transform);
        //         _layers[i] = viewLayer;
        //     }
        // }
        //
        // private void OnViewProxyShow(Event evt)
        // {
        //     Emit(ViewManagerEvent.ViewProxyShow, evt.args[0]);
        // }

        // private void PauseAllViewBehind(ViewContainer viewContainer)
        // {
        //     if (IsFullScreenView(viewContainer))
        //     {
        //         int index = (int) viewContainer.viewDefine.layerType;
        //         for (int i = 0; i <= index; ++i)
        //         {
        //             List<ViewContainer> viewList = _layers[i].GetViewList();
        //             int viewIndex = viewList.IndexOf(viewContainer);
        //             if (viewIndex == -1)
        //             {
        //                 viewIndex = viewList.Count;
        //             }
        //             for (int j = 0; j < viewIndex; ++j)
        //             {
        //                 ViewContainer findViewContainer = viewList[j];
        //                 findViewContainer.Pause();
        //             }
        //         }
        //     }
        // }
        //
        // private void ResumeAllViewBehind(ViewContainer viewContainer)
        // {
        //     if (IsFullScreenView(viewContainer) && IsTopFullScreenView(viewContainer))
        //     {
        //         int index = (int) viewContainer.viewDefine.layerType;
        //         for (int i = index; i >= 0; --i)
        //         {
        //             List<ViewContainer> viewList = _layers[i].GetViewList();
        //             int viewIndex = viewList.IndexOf(viewContainer);
        //             if (viewIndex == -1)
        //             {
        //                 viewIndex = viewList.Count;
        //             }
        //             for (int j = viewIndex - 1; j >= 0; --j)
        //             {
        //                 ViewContainer findViewContainer = viewList[j];
        //                 if (findViewContainer.isShowing)
        //                 {
        //                     findViewContainer.Resume();
        //                     if (IsFullScreenView(findViewContainer))
        //                     {
        //                         return;
        //                     }
        //                 }
        //             }
        //         }
        //     }
        // }
        //
        // private bool IsFullScreenView(ViewContainer viewContainer)
        // {
        //     ViewType viewType = viewContainer.viewDefine.viewType;
        //     return viewType == ViewType.Modal || viewType == ViewType.FullScreen;
        // }
        //
        // public bool IsTopFullScreenView(ViewContainer viewContainer)
        // {
        //     int index = (int) viewContainer.viewDefine.layerType;
        //     for (int i = index; i < _layers.Length; ++i)
        //     {
        //         List<ViewContainer> viewList = _layers[i].GetViewList();
        //         int viewIndex = viewList.IndexOf(viewContainer);
        //         if (viewIndex == -1)
        //         {
        //             viewIndex = 0;
        //         }
        //         for (int j = viewIndex + 1; j < viewList.Count; ++j)
        //         {
        //             ViewContainer findViewContainer = viewList[j];
        //             if (findViewContainer.isShowing && IsFullScreenView(findViewContainer))
        //             {
        //                 Debugger.Log("is not top view: " + viewIndex + ", " + viewContainer.viewDefine.name);
        //                 return false;
        //             }
        //         }
        //     }
        //     return true;
        // }
    }
}